package com.yizhubao.app.fragments;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.transition.Visibility;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yizhubao.app.R;
import com.yizhubao.app.activitys.AuthActivity;
import com.yizhubao.app.activitys.ExplainActivity;
import com.yizhubao.app.activitys.PayActivity;
import com.yizhubao.app.activitys.RecordDetailActivity;
import com.yizhubao.app.activitys.WebActivity;
import com.yizhubao.app.activitys.WelcomeActivity;
import com.yizhubao.app.activitys.WelfareActivity;
import com.yizhubao.app.activitys.home.NormalSwipeActivity;
import com.yizhubao.app.activitys.home.ProdSwipeActivity;
import com.yizhubao.app.adapters.HomeAdapter;
import com.yizhubao.app.base.BaseFragment;
import com.yizhubao.app.beans.ListRecordBean;
import com.yizhubao.app.events.LoginEvent;
import com.yizhubao.app.events.PayEvent;
import com.yizhubao.app.events.RecordEvent;
import com.yizhubao.app.presenters.ListRecordPresenter;
import com.yizhubao.app.utils.Constants;
import com.yizhubao.app.utils.Utils;
import com.yizhubao.app.views.ListRecordView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import h.framework.pacy.utils.DateUtil;
import h.framework.pacy.utils.LogUtil;
import h.framework.pacy.utils.ScreenUtil;
import h.framework.pacy.views.recyclerview.DividerDecoration;
import h.framework.pacy.views.recyclerview.HRecyclerView;

/**
 * 创建人: PACY
 * 创建时间: 6/4/21 10:25 AM
 * 邮箱: pengwwe457621023@qq.com
 * 类描述: 首页fragment
 */
public class HomeFragment extends BaseFragment implements ListRecordView {

    @BindView(R.id.home_hrv)
    HRecyclerView homeHrv;
    HomeAdapter mAdapter;
    LinearLayoutManager mManager;//布局管理器
    View headerView;//列表头布局，包含banner等
    View footerView;//底部布局

    @BindView(R.id.normal_rel)
    RelativeLayout normal_rel;

    private LinearLayout normal_lin;
    private LinearLayout prod_lin;

    TextView homeLabRight_tv;
    TextView homeLabLeft_tv;
    LinearLayout labLin;
    TextView homeLabpay_tv;
    @BindView(R.id.homeLabRight2_tv)
    TextView homeLabRight2_tv;

    ListRecordPresenter presenter;

    public static HomeFragment newInstance(String title) {

        Bundle args = new Bundle();
        args.putString("title", title);
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        initAdapter();
        initRecyclerView();
        initHeaderView();
        initFooterView();
        presenter = new ListRecordPresenter();
        presenter.attachView(this);
    }

    @Override
    protected void initData() {
        sendRequest();
    }

    /**
     * 发送请求
     */
    private void sendRequest() {
        if (!Utils.isLogin()) {

            normal_rel.setVisibility(View.VISIBLE);
            homeHrv.setVisibility(View.GONE);

            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", 999);
        map.put("pageNum", 1);
        presenter.sendListRequest(map);
        showLoading();
    }

    /**
     * 初始化adapter
     */
    private void initAdapter() {
        mAdapter = new HomeAdapter();
        mAdapter.isFirstOnly(true);
//        mAdapter.setPreLoadNumber(5);
        //设置item动画
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        //设置数据为空时显示headerview
        mAdapter.setHeaderFooterEmpty(true, false);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (Utils.isPay()) {
                    if(Utils.isIdCard()){
                        Bundle bundle = new Bundle();
                        bundle.putString("recordId", mAdapter.getItem(position).getId() + "");
                        startActivity(getActivity(), RecordDetailActivity.class, bundle);
                    }else{
                        Bundle bundle=new Bundle();
                        bundle.putInt("jumpType",2);
                        bundle.putString("recordId",mAdapter.getItem(position).getId().toString());
                        startActivity(getActivity(), AuthActivity.class,bundle);
                    }

                } else {
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 2);
                    bundle.putString("recordId",mAdapter.getItem(position).getId().toString());
                    startActivity(getActivity(),PayActivity.class,bundle);
                }
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        LogUtil.i("登录啦");
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent event) {
        LogUtil.i("支付成功啦!");
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecordEvent(RecordEvent event) {
        LogUtil.i("列表变动!");
        initData();
    }

    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        mManager = new LinearLayoutManager(getActivity());
        homeHrv.setLayoutManager(mManager);
        homeHrv.setAdapter(mAdapter);
        //添加分割线
        DividerDecoration decoration = new DividerDecoration(getResources().getColor(R.color.transparent), ScreenUtil.dp2px(10));
        homeHrv.addItemDecoration(decoration);
    }


    /**
     * 添加头布局
     */
    private void initHeaderView() {

        if (headerView == null) {
            headerView = LayoutInflater.from(getActivity()).inflate(R.layout.home_header_view, (ViewGroup) homeHrv.getRecyclerView().getParent(), false);
            normal_lin = headerView.findViewById(R.id.normal_lin);
            normal_lin.setOnClickListener(v -> startActivity(getContext(), NormalSwipeActivity.class));

            prod_lin = headerView.findViewById(R.id.prod_lin);
            prod_lin.setOnClickListener(v -> {
                startActivity(getActivity(), ProdSwipeActivity.class);
            });
        }
        if (mAdapter.getHeaderLayoutCount() < 1) {
            mAdapter.addHeaderView(headerView);
        }
    }

    /**
     * 添加底布局
     */
    private void initFooterView() {

        if (footerView == null) {
            footerView = LayoutInflater.from(getActivity()).inflate(R.layout.home_fooder_view, (ViewGroup) homeHrv.getRecyclerView().getParent(), false);
            homeLabRight_tv = footerView.findViewById(R.id.homeLabRight_tv);
            homeLabRight_tv.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("title", "联系客服");
                bundle.putString("url", Constants.LIANXIKEFU);
                startActivity(getActivity(), WebActivity.class, bundle);
            });
            homeLabLeft_tv = footerView.findViewById(R.id.homeLabLeft_tv);
            homeLabLeft_tv.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("title", "如何使用");
                bundle.putString("url", Constants.QUESTION);
                startActivity(getActivity(), WebActivity.class, bundle);
            });

            homeLabpay_tv = footerView.findViewById(R.id.homeLabpay_tv);
            homeLabpay_tv.setOnClickListener(v -> {
                startActivity(getActivity(), ExplainActivity.class);
            });
            labLin = footerView.findViewById(R.id.labLin);
        }
        if (mAdapter.getFooterLayoutCount() < 1) {
            mAdapter.addFooterView(footerView);
        }
    }

    @OnClick(value = {R.id.normal_cad, R.id.pro_cad, R.id.homeLabRight2_tv, R.id.homeLabLeft2_tv})
    public void click(View v) {
        if (v.getId() == R.id.normal_cad) {
            startActivity(getContext(), NormalSwipeActivity.class);
        } else if (v.getId() == R.id.pro_cad) {
            startActivity(getActivity(), ProdSwipeActivity.class);
        } else if (v.getId() == R.id.homeLabRight2_tv) {
            if (homeLabRight2_tv.getText().equals("公益通道")) {
                startActivity(getActivity(), WelfareActivity.class);
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("title", "联系客服");
                bundle.putString("url", Constants.LIANXIKEFU);
                startActivity(getActivity(), WebActivity.class, bundle);
            }

        } else if (v.getId() == R.id.homeLabLeft2_tv) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "如何使用");
            bundle.putString("url", Constants.QUESTION);
            startActivity(getActivity(), WebActivity.class, bundle);
        }
    }

    @Override
    public int setLayoutResourceID() {
        return R.layout.home_fragment;
    }

    @Override
    public void onListSuccess(ListRecordBean recordBean) {
        LogUtil.i(recordBean.getList().size() + "-----");
        if (recordBean.getList().size() > 0) {
            normal_rel.setVisibility(View.GONE);
            homeHrv.setVisibility(View.VISIBLE);
            mAdapter.setNewData(recordBean.getList());
        } else {
            normal_rel.setVisibility(View.VISIBLE);
            homeHrv.setVisibility(View.GONE);
        }
        //已支付
        if (Utils.isPay()) {
            //有内容
            if (recordBean.getList().size() > 0) {
                labLin.setVisibility(View.VISIBLE);
                homeLabpay_tv.setVisibility(View.GONE);
            } else {
                //无内容
                homeLabRight2_tv.setText("联系客服");
            }
        } else {
            //未支付
            //有内容
            if (recordBean.getList().size() > 0) {
                labLin.setVisibility(View.GONE);
                homeLabpay_tv.setVisibility(View.VISIBLE);
            } else {
                //无内容
                homeLabRight2_tv.setText("公益通道");
            }
        }
        setFooterHeight();
    }

    /**
     * 放大缩小动画
     */
    private void startAnimation(){
        int time=2000;
        ObjectAnimator animX = ObjectAnimator.ofFloat(homeLabpay_tv, "scaleX", 1.0f, 1.1f, 1.0f);
        ObjectAnimator animY = ObjectAnimator.ofFloat(homeLabpay_tv, "scaleY", 1.0f, 1.1f, 1.0f);
        animX.setDuration(time);
        animY.setDuration(time);
        animX.setRepeatCount(ObjectAnimator.INFINITE);
        animY.setRepeatCount(ObjectAnimator.INFINITE);
        animX.start();
        animY.start();
    }



    /**
     * 设置底部视图高度
     */
    int footerViewHeight;
    private void setFooterHeight() {
        homeHrv.post(() -> {
            int recyclerViewHeight = homeHrv.getHeight();
            // int footerViewTop = mFooterView.getTop();
            // 由于 BaseQuickAdapter 的 addFooterView 方法是将 footerView 添加到一个 LinearLayout 里面，
            // 然后再把这个 LinearLayout 添加到 RecyclerView 的底部。所以在这里算 footerView 顶部到 RecyclerView 的顶部距离时，
            // 就要先得到这个 footerView 的 父布局 LinearLayout，然后再通过 getTop 方法就可以得到 top 值。
            // ListView 的 BaseAdapter 自带 addFooterView，此方法里面没有嵌套 ViewGroup,可以通过 footerView.getTop() 直接得到 top 值。
            int footerViewTop = mAdapter.getFooterLayout().getTop();

            ViewGroup.LayoutParams layoutParams = footerView.getLayoutParams();
            layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            footerView.setLayoutParams(layoutParams);

            if(footerViewHeight==0){
                footerViewHeight  = footerView.getHeight();
            }
            LogUtil.i("recyclerViewHeight=" + recyclerViewHeight + "\nfooterViewTop=" + footerViewTop + "\nfooterViewHeight=" + footerViewHeight);

            if (footerViewTop > 0) {
                if (recyclerViewHeight - footerViewTop > footerViewHeight) {
                    ViewGroup.LayoutParams layoutParams2 = footerView.getLayoutParams();
                    layoutParams2.height = recyclerViewHeight - footerViewTop - 50;
                    footerView.setLayoutParams(layoutParams2);
                }
            }

            if(homeLabpay_tv.getVisibility()==View.VISIBLE){
                startAnimation();
            }
        });

    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if(homeHrv.getHeight()==0){
                setFooterHeight();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
            setFooterHeight();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
